package com.infoblazer.grailsmaps

import grails.web.JSONBuilder

class StateController {
  def scaffold = true

  def list = {

    if (params.format == 'json') {
      def stateList = State.list()


      def builder = new JSONBuilder()
      def result = builder.build {
        states = array {
          for (s in stateList) {
            state id: s.id, stateName: s.stateName
          }
        }
      }
      if (params.jsoncallback){
      render params.jsoncallback + "(" + result.toString() + ")"
      }
      else{
      render result.toString()         
      }
    }
    else {
      render(template: "list", model: [states: State.list(), stateId: params.stateId])
    }
  }

  def listCities = {

    State state
    if (params.id) {
      state = State.get(params.id);
    }
    String searchString = params.searchText ? '%' + params.searchText + '%' : '%'
    def cities
    def cityCount
    if (state) {
      cityCount = City.countByStateAndCityNameLike(state, searchString)
      cities = City.findAllByStateAndCityNameLike(state, searchString,
              [max: params.max && Integer.valueOf(params.max) <= 100 ? params.max : 10,
                      sort: params.sort ? params.sort : 'cityName',
                      order: params.order ? params.order : 'asc',
                      offset: params.offset
              ]);
    }
    else {
      cityCount = City.countByCityNameLike(searchString)
      cities = City.findAllByCityNameLike(searchString,
              [max: params.max && Integer.valueOf(params.max) <= 100 ? params.max : 10,
                      sort: params.sort ? params.sort : 'cityName',
                      order: params.order ? params.order : 'asc',
                      offset: params.offset
              ]);

    }
    if (params.format == 'json') {
      buildCitiesJson(params.jsoncallback, cities, cityCount)

    }
    else {
      [cities: cities, state: state, stateId: state?.id, cityCount: cityCount, searchText: params.searchText]
    }
  }

  private void buildCitiesJson(jsoncallback, cityList, cityCount) {

    def builder = new JSONBuilder()
    def result = builder.build {
      cities = array {
        for (c in cityList) {
          city = {
            id = c.id
            cityName = c.cityName
            latitude = c.latitude
            longitude = c.longitude
            state = {
              id = c.state.id
              stateAbbrev=c.state.stateAbbrev
            }
          }
        }
      }
      numberOfCities = cityCount

    }


      if (jsoncallback){
        render jsoncallback + "(" + result.toString() + ")"
      }
    else{
      render  result.toString()
      }
  }


}
